package com.gexiaobao.pigeon.ui.fragment.mine.tools.line

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapView
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.Polyline
import com.amap.api.maps.model.PolylineOptions
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.model.bean.FlyWeatherInfoResponse
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.FragmentLineMatchBinding
import com.gexiaobao.pigeon.viewmodel.MatchLineQueryViewModel
import java.math.RoundingMode
import java.text.DecimalFormat

/**
 * @Author      : hxw
 * @Date        : 2023/6/1 9:23
 * @Describe    : 赛线
 */
class FragmentLineMatch : BaseFragment<MatchLineQueryViewModel, FragmentLineMatchBinding>(), AMap.OnMapLoadedListener {

    var addPolyline: Polyline? = null
    var latitude: Double = 0.00
    var longitude: Double = 0.00

    //声明mLocationClient对象
    lateinit var mLocationClient: AMapLocationClient

    //声明mLocationOption对象
    lateinit var mLocationOption: AMapLocationClientOption

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.mineToolsMapDis.onCreate(savedInstanceState)

        //设置是否只定位一次,默认为false
        mLocationClient = AMapLocationClient(context)
        //初始化定位参数
        mLocationOption = AMapLocationClientOption()
        //设置定位监听
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.interval = 2000
        //设置定位参数
        mLocationOption.isOnceLocation = true
        mLocationClient.setLocationOption(mLocationOption)
        mDatabind.mineToolsMapDis.map.setOnMapLoadedListener(this)
    }

    companion object {
        fun newInstance(flyWeatherBean: FlyWeatherInfoResponse): FragmentLineMatch {
            val fragment = FragmentLineMatch()
            val bundle = Bundle()
            fragment.arguments = bundle
            bundle.putParcelable("fly_weather_result", flyWeatherBean)
            return fragment
        }
    }

    override fun onMapLoaded() {
        try {
            val flyWeatherResult = arguments?.getParcelable<FlyWeatherInfoResponse>("fly_weather_result")
            if (flyWeatherResult != null) {
                initLatLngDis(flyWeatherResult)
            }
        } catch (e: Exception) {
            RxToast.showToast("获取赛线信息错误101")
            e.printStackTrace()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initLatLngDis(flyBean: FlyWeatherInfoResponse) {
        val df = DecimalFormat("0.00")
        df.roundingMode = RoundingMode.HALF_UP

        if (addPolyline != null) {
            addPolyline!!.remove()
            addPolyline = null
        }
        mDatabind.mineToolsMapDis.map.clear()
        var small_lon = flyBean.liberateLongitude.toDouble()
        var small_lat = flyBean.liberateLatitude.toDouble()
        var big_lon = flyBean.homeLongitude.toDouble()
        var big_lat = flyBean.homeLatitude.toDouble()

        if (small_lon > big_lon) {
            val temp_lon = small_lon
            small_lon = big_lon
            big_lon = temp_lon
        }

        if (small_lat > big_lat) {
            val temp_lat = small_lat
            small_lat = big_lat
            big_lat = temp_lat
        }

        mDatabind.mineToolsMapDis.map.moveCamera(
            CameraUpdateFactory.newLatLngBounds(
                LatLngBounds(LatLng(small_lat, small_lon), LatLng(big_lat, big_lon)),
                10
            )
        )

        if (flyBean.weatherList.size < 2) {
            RxToast.showToast("放飞赛点异常")
            return
        }

        val latLngList = ArrayList<LatLng>()
        flyBean.weatherList.forEachIndexed { _, it ->
            val markerOption2 = MarkerOptions()
            val latLng = LatLng(it.latitude.toDouble(), it.longitude.toDouble())
            markerOption2.position(latLng)
            markerOption2.draggable(false)
            val view = layoutInflater.inflate(R.layout.kc_distance_popup, null)
            val tv = view.findViewById<TextView>(R.id.location)

            var strDistance = "${Util.distanceMath("" + it.distance)}公里"
            if (it.distance == 0.0) {
                strDistance = "归巢点"
            }
            tv.text = "${it.district}  ${it.weather}\n" + "$strDistance\n" + "${it.winddirection}风${it.windpower}级"

            view.findViewById<TextView>(R.id.location)
            markerOption2.icon(BitmapDescriptorFactory.fromView(view))
            mDatabind.mineToolsMapDis.map.addMarker(markerOption2)
            latLngList.add(latLng)
        }

        val polylineOptions = PolylineOptions()
            .addAll(latLngList)
            .width(8.0f)
            .color(Color.argb(255, 86, 155, 255))
            .setDottedLine(false)
        addPolyline = mDatabind.mineToolsMapDis.map.addPolyline(polylineOptions)
    }

    override fun onResume() {
        super.onResume()
        if (mDatabind.mineToolsMapDis != null) {
            mDatabind.mineToolsMapDis.onResume()
        }
    }

    override fun onPause() {
        super.onPause()
        if (mDatabind.mineToolsMapDis != null) {
            mDatabind.mineToolsMapDis.onPause()
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mDatabind.mineToolsMapDis.onSaveInstanceState(outState)
    }
}